﻿using System;

namespace StackExchange.Redis.Extensions.Lock
{
    internal class LockHeartbeat : IDisposable
    {
        private IDatabase _redisDb;
        private System.Timers.Timer _timer;
        private string _key;
        private double _delaySeconds;

        public LockHeartbeat(IDatabase redisDb, string key, int expireSeconds)
        {
            _delaySeconds = expireSeconds;
            _redisDb = redisDb;
            _key = key;
            _timer = new System.Timers.Timer();
            _timer.Interval = TimeSpan.FromSeconds(_delaySeconds - 1).TotalMilliseconds;
            _timer.AutoReset = true;
            _timer.Elapsed += _timer_Elapsed;
            _timer.Start();
        }

        private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                _redisDb.KeyExpire(_key, TimeSpan.FromSeconds(_delaySeconds));

            }
            catch
            {
            }
        }

        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _timer.Stop();
                    _timer.Dispose();
                }

                disposedValue = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
        }
    }
}
